import { FormFieldWrapper } from '@components/common/formFieldWrapper/formFieldWrapper'
import { ReactComponentExt } from '@helpers/ReactExt'
import utils from '@helpers/utils'
import { BaseProps } from '@store/store'
import { Button, Col, Form, Row } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import moment from 'moment'
import * as React from 'react'
import { formFieldConfig } from './constantsConfig'
import * as styles from './createSubjectPage.less'

// tslint:disable-next-line:no-empty-interface
export interface CreateSubjectPageProps extends BaseProps, FormComponentProps {

}

interface CreateSubjectPageState {
  editable: boolean,
  subjectData: ViewModels.DanceClassData | {}
}

class CreateSubjectPage extends ReactComponentExt<CreateSubjectPageProps, CreateSubjectPageState> {
  public init() {
    this.state = {
      editable: true,
      subjectData: {}
    }
    this.handleFormCancel = this.handleFormCancel.bind(this)
    this.handleFormSubmit = this.handleFormSubmit.bind(this)
  }

  public async componentDidMount() {
    // todo
    const { subjectId } = this.query
    if (subjectId) {
      await this.getSubjectById(subjectId)
    }
  }

  public render() {
    const { form } = this.props
    const { subjectData } = this.state
    const { action } = this.query
    return (
      <div className={styles.wrapper}>
        <h1>创建学校学科</h1>
        <Form onSubmit={this.handleFormSubmit}>
          <Row gutter={24}>
            <FormFieldWrapper
              data={subjectData}
              action={action}
              span={12}
              form={form}
              formFieldConfig={formFieldConfig}
            />
          </Row>
          <Row>
            <span className={styles.text}>每一项前面标星号(*)为必填项 </span>
            <Col span={24} style={{ textAlign: 'right' }}>
              <Button onClick={this.handleFormCancel}>取消</Button>
              {
                action === 'look' ? '' :
                  <Button style={{ marginLeft: 8 }} type='primary' htmlType='submit'>{
                    action === 'edit' ? '修改' : '创建'
                  }</Button>
              }
              {/* <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}>
                  Collapse <Icon type={this.state.expand ? "up" : "down"} />
                </a> */}
            </Col>
          </Row>
        </Form>
      </div>
    )
  }

  private async getSubjectById(subjectId: number) {
    const { code, message, data: { subject } } = await this.api.getDanceClassById(subjectId)
    if (code !== 0) {
      this.$message.error(message, 5)
      return
    }
    const { schooltime, name, cover, banners } = subject
    const b = JSON.parse(banners) as string[]
    const subjectData: ViewModels.DanceClassData = {
      ...subject,
      dspSchooltime: schooltime ? moment(schooltime) : null,
      dspCoverFile: utils.convertToAntdFile(name, [cover]),
      dspBannersFile: utils.convertToAntdFile(name, b)
    }
    await this.setState({ subjectData })
  }

  private handleFormSubmit(e: React.MouseEvent) {
    e.stopPropagation()
    e.preventDefault()
    const { form, history } = this.props
    const { action, subjectId } = this.query
    form.validateFields(async (err, values: ViewModels.DanceClassData) => {
      if (err) {
        this.$message.error('请检查数据是否完整', 5)
        return
      }
      const { dspSchooltime, dspCoverFile, dspBannersFile } = values
      values.schooltime = moment(dspSchooltime!).unix()
      const { status: s, response: r, originUrl: o } = dspCoverFile[0]
      if (!r && s === 'done') {
        values.cover = o
      } else {
        values.cover = dspCoverFile[0].response!.data.url
      }
      if (dspBannersFile && dspBannersFile.length > 0) {
        const banners = dspBannersFile.map((item) => {
          const { status, response, originUrl } = item
          if (!response && status === 'done') {
            return originUrl
          }
          return item.response!.data.url
        })
        values.banners = JSON.stringify(banners)

      }
      // 保持和后端 Model 一致性
      delete values.dspSchooltime
      delete values.dspCoverFile
      delete values.dspBannersFile
      if (action === 'edit' && subjectId) {
        const { code, message } = await this.api.updateSubjectInfo(subjectId, values)
        if (code !== 0) {
          this.$message.error(message, 5)
          return
        }
        this.$message.success('创建成功')
      } else {

        const { code, message } = await this.api.createSubject(values)
        if (code !== 0) {
          this.$message.error(message, 5)
          return
        }
        this.$message.success('修改成功')
      }

      history!.push('/subject/list')
    })
  }

  private handleFormCancel() {
    const { history } = this.props
    history!.push('/subject/list')
  }
}

export default Form.create<CreateSubjectPageProps>({ name: 'subject_create_form' })(CreateSubjectPage)
